import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

public class SnakeHead  extends GameObj{
    private String direction = "right";
    public String getDirection() {
        return direction;
    }
    public void setDirection(String direction) {
        this.direction = direction;
    }

    public void changeDirection(KeyEvent keyEvent){
        switch (keyEvent.getKeyCode()) { //获取按键
            case KeyEvent.VK_W: //表示w按键
                direction = "up";
                img = GameUtils.upImg;
                break;
            case KeyEvent.VK_S: //表示w按键
                direction = "down";
                img = GameUtils.downImg;
                break;
            case KeyEvent.VK_A: //表示w按键
                direction = "left";
                img = GameUtils.leftImg;
                break;
            case KeyEvent.VK_D: //表示w按键
                direction = "right";
                img = GameUtils.rightImg;
                break;
            default:
                break;
        }
    }
    public void move(){
        ArrayList<SnakeBody> snakeBodyList = this.frame.snakeBodyList;

        if(this.frame.foodObj.x == this.x &&
                this.frame.foodObj.y == this.y){
            this.frame.foodObj = this.frame.getRandomFood();
            snakeBodyList.add(new SnakeBody(GameUtils.body,0,0,this.frame));
        }

        for (int i = snakeBodyList.size() - 1; i >= 0 ; i--) {
            if(i == 0){
                snakeBodyList.get(i).x = this.x;
                snakeBodyList.get(i).y = this.y;
            }
            else {
                snakeBodyList.get(i).x = snakeBodyList.get(i - 1).x;
                snakeBodyList.get(i).y = snakeBodyList.get(i - 1).y;
            }
        }



        switch (direction){
            case "right":
                x += frame.step;//向右移动一格
                x = (x > frame.frameSize) ? 0 : x;
                break;
            case "left":
                x -= frame.step;//向左移动一格
                x = (x < 0) ? frame.frameSize : x;
                break;
            case "up":
                y -= frame.step;//向上移动一格
                y = (y < 0) ? frame.frameSize : y;
                break;
            case "down":
                y += frame.step;//向下移动一格
                y = (y >  frame.frameSize) ? 0: y;
                break;
        }
    }
    public SnakeHead(Image img, int x, int y, GameFrame frame) {
        super(img, x, y, frame);
        this.frame.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                changeDirection(e);
            }
        });
    }
    @Override
    public void paintSelf(Graphics g){
        super.paintSelf(g);
        move();
    }
}
